<template>
	<view>
		<image
			class="wrap-bg-img"
			mode="widthFix"
			:src="$wanlshop.oss(common.modulesData.homeModules.page ? common.modulesData.homeModules.page.style.navigationBackgroundImage : '')"
		/>
		
		<wrapTopHeadVue @onTopHeight="onTopHeight" :addressID="address_id"
			:bgImg="$wanlshop.oss(common.modulesData.homeModules.page ? common.modulesData.homeModules.page.style.navigationBackgroundImage : '')"
		/>
		
		<swiper class="wanlshop-container__main" :current-item-id="currentItemId" :style="{
			height: windowHeight + 'px'
		}" @change="changeCurrent" @animationfinish="animationFinish" v-show="is_show">
			<!-- 主页 -->
			<swiper-item item-id="home">	
				<wanl-shop-page
					:windowHeight="windowHeight"
					:headHeight="topHeight"
					:headTop="topHeight"
					:pageModules="common.modulesData.homeModules"
					:adData="common.adData"
				/>
			</swiper-item>
		</swiper>
		
		<block v-if="loginState">
			<view class="noLogin" v-if="!loginType">
				<view class="loginText">登录领取更多好礼</view>
				<view class="goLogin" @click="goLogin">去登录</view>
			</view>
		</block>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import wrapTopHeadVue from "@/components/home/homeTopHead.vue";
	import wanlShopPage from '@/components/wanl-shop/page';
	import wanlShopFind from '@/components/wanl-shop/find';
	import wanlShopCategory from '@/components/wanl-shop/category';
	import HeadNavigation from '@/components/HeadNavigation.vue'

	export default {
		components: {
			wrapTopHeadVue,
			wanlShopPage,
			wanlShopFind,
			wanlShopCategory,
			HeadNavigation,
		},
		computed: {
			...mapState(['common', 'user', 'update'])
		},
		data() {
			return {
				topHeight: 0, //顶部高度
				address_id: "0", //地址ID
				is_show:true,
				modalName: '',
				scrollAnimation: 300,
				headHeight: 20,
				windowHeight: 0,
				headTop: 0,
				currentItemId: 'home',
				currentData: {},
				scrollLeft: 0,
				contentText: {
					contentdown: '下拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的'
				},
				headState: 1,
				loginState: false,
				homeHeaderPositioning: '',
				address: '小石子集市',
				loginType: '',
				shopType: false,
				selectedAddress: {},
				
			};
		},
		onShow() {
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(false);
			// #endif
			// 计算页面尺寸
			let sys = this.$wanlshop.wanlsys();
			this.headTop = sys.top;
			this.headHeight = sys.height + uni.upx2px(80);
			this.windowHeight = sys.windowHeight;
			setTimeout(() => {
				uni.setNavigationBarColor({
					frontColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarTextStyle : '',
					backgroundColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarBackgroundColor : ''
				});
			}, 200);
			
			
			
			if (uni.getStorageSync('wanlshop:user')) {
				this.loginType = uni.getStorageSync('wanlshop:user');
			}
		},
		onReady() {
			let that = this
			uni.$on('address', function(data) {
				that.address_id = data.id
				
				var longitude = uni.getStorageSync('longitude')
				var latitude = uni.getStorageSync('latitude')
				
				uni.request({
					url: '/wanlshop/user/profile',
					method: 'POST',
					data: {
						longitude: longitude,
						latitude: latitude,
					},
					success: res => {
						// 更新 homeModules 数据
						this.$store.commit('common/setHomeModules', res.data.homeModules);
					}
				});
			});
		},
		onLoad(query) {
			if (query.hasOwnProperty("q")) {
				const url = decodeURIComponent(query.q);
				var obj = {};
				url.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v));
				
				if (obj.hasOwnProperty("pid")) {
					if (uni.getStorageSync('wanlshop:user')) {
						this.$commonNetwork.onBindParent(obj.pid);
					} else {
						this.$filters.pid = obj.pid;
						this.goLogin();
					}
				}
			}
			// 判断是否小程序来源
			if (query.hasOwnProperty('scene')) {
				let scene = decodeURIComponent(query.scene);
				scene = this.$wanlshop.getParam(scene);
				console.log('微信小程序：', scene);
			}

			uni.request({
				url: '/wanlshop/common/init',
				method: 'GET',
				success: res => {
					console.log(res.data)
					console.log(res.data.modulesData.homeModules.page.style)
					this.headState = res.data.modulesData.homeModules.page.style.homeHeaderStyle
					this.loginState = res.data.modulesData.homeModules.page.style.homeLogin
					uni.setStorageSync('shopType', res.data.appStyle.goods_store_label)
					this.homeHeaderPositioning = res.data.modulesData.homeModules.page.style
						.homeHeaderPositioning || ''
				}
			});
			
			if (uni.getStorageSync('wanlshop:user')) {
				this.getAdd()
			}
		},
		methods: {
			/**
			 * 顶部高度
			 */
			onTopHeight(height) {
				this.topHeight = height;
			},
			
			
			goLogin() {
				this.$wanlshop.to(`/pages/user/auth/auth`);
			},
			getAdd() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						// 126.56279 45.80825
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						var longitude = res.longitude
						var latitude = res.latitude
						uni.setStorageSync('longitude', longitude)
						uni.setStorageSync('latitude', latitude)
						this.getDetails();
						uni.request({
							url: '/wanlshop/user/profile',
							method: 'POST',
							data: {
								longitude: longitude,
								latitude: latitude,
							},
							success: res => {
								this.$store.commit('common/setHomeModules', res.data.homeModules);
							}
						});

					},
					fail: (res) => {
						console.log(res)
						console.log('失败:' + res)
					}
				})
			},
			getDetails() {
				var longitude = uni.getStorageSync('longitude')
				var latitude = uni.getStorageSync('latitude')
				var amapKey = '41ed00c06016a4c19834abf849829137'
				const amapUrl =
					`https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude},${latitude}&key=${amapKey}`;
				// 发起请求
				uni.request({
					url: amapUrl,
					success: (res) => {
						if (res.statusCode === 200 && res.data.status === '1') {
							console.log('成功获取地址信息:', );
							console.log('成功获取地址信息:', res.data.regeocode.formatted_address);
							var address = res.data.regeocode.addressComponent.district;
							if (address) {
								this.address = address
							} else {
								this.address = res.data.regeocode.formatted_address
							}
							// 在这里处理返回的详细地址信息
						} else {
							console.error('获取地址失败:', res);
						}
					},
					fail(err) {
						console.error('请求失败:', err);
					}
				});
			},
			...mapActions({
				download: 'update/download', // 立即下载
				ignore: 'update/ignore' // 忽略更新
			}),
			// 选择Tag
			handleSelect(id, index) {
				this.currentItemId = id;
				this.scrollLeft = (index - 1) * 50;
			},
			// 动画
			animationFinish(e) {
				//#ifdef APP-PLUS
				this.changeCurrent(e);
				//#endif
			},
			// 滚动的tag
			changeCurrent(e) {

				this.currentItemId = e.detail.currentItemId;
				this.scrollLeft = (e.detail.current - 1) * 50;
			},
			// 弹出层
			handleModal(name) {
				// 滚动分享
				if (name == 'share') {
					setTimeout(() => {
						this.scrollAnimation = 0;
					}, 300);
				}
				// 强制关闭海报
				if (this.modalName == 'share') {
					this.$refs.wanlShare.closePoster();
				}
				this.modalName = this.modalName ? null : name;
			},
			// 扫码
			scanCode() {
				// #ifndef H5
				uni.scanCode({
					success: res => {
						let query = this.$wanlshop.getParam(res.result),
							id = query.id;
						switch (query.qr) {
							case 'g':
								this.onGoods(id);
								break;
							case 'gr':
								this.$wanlshop.to(
									`/pages/apps/groups/goods?id=${id}&groups_id=${query.groups_id}`);
								break;
							case 'u':
								this.$wanlshop.to(`/pages/user/info?id=${id}`);
								break;
							case 'fu':
								this.$wanlshop.to(`/pages/apps/find/user?id=${id}`);
								break;
							case 'c':
								this.$wanlshop.on('/pages/category');
								break;
							case 'p':
								this.$wanlshop.to(`/pages/page/index?id=${id}`);
								break;
							case 's':
								this.onShop(id);
								break;
							case 'live':
								// #ifdef APP-PLUS || MP-WEIXIN
								this.$wanlshop.auth(`/pages/shop/live/live`);
								// #endif
								// #ifndef APP-PLUS || MP-WEIXIN
								this.$wanlshop.msg('目前只开放App和微信小程序直播');
								// #endif
								break;
							case 'chat':
								this.toChat(id);
								break;
						}
					}
				});
				// #endif
				// #ifdef H5
				this.$wanlshop.msg('暂不支持H5扫码');
				// #endif
			},
			// 搜索
			handleSearch(text) {
				this.$wanlshop.to(`/pages/page/search?type=goods&keywords=${text}`, 'fade-in', 100);
			},
			//禁止父元素滑动 1.0.3升级
			moveHandle() {}
		}
	};
</script>

<style lang="scss">
	.wrap-bg-img {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		z-index: -1;
	}
	
	.wrap {
		--bottom-height: 120rpx;
		box-sizing: border-box;
		height: 100vh;
	}
	
	
	.noLogin {
		width: 690rpx;
		height: 90rpx;
		border-radius: 50rpx;
		background: rgba(0, 0, 0, 0.7);
		position: fixed;
		bottom: 30rpx;
		z-index: 999;
		left: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.loginText {
			font-size: 30rpx;
			color: #FFFFFF;
			margin-left: 30rpx;
		}

		.goLogin {
			width: 133rpx;
			height: 64rpx;
			border-radius: 50rpx;
			background: #84BD00;
			font-size: 30rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-right: 30rpx;
		}
	}
</style>